# -*- encoding: utf-8 -*-
import socket
import time
import random
import threading
import queue

# 接收方端口
ip = '114.212.84.31'
port = 41998

conn = True

# ip_sock.bind((self_ip, self_port))
init_msg = "Initial: physical"

test = queue.Queue(10)
test.queue.clear()
_queue_lock = threading.Lock()

def create_reply():
    if (test.empty()):
        print("empty queue")
        return None
    
    _queue_lock.acquire()
    data = test.get()
    _queue_lock.release()
    x = random.random()>0.5
    ret = "! {}".format(x)
    print("answer [{}] = {}".format(data,ret))
    return ret

def udp_send(ip_sock):
    ip_sock.sendto(init_msg.encode('utf-8'),(ip, port))

    while True:
        data = input("input>")
        if data=='quit' or data == 'shutdown':
            if (conn): ip_sock.sendto(data.encode('utf-8'),(ip, port))
            break
        elif data == 'check':
            data = create_reply()
        
        if (conn): ip_sock.sendto(data.encode('utf-8'),(ip, port))
        
    ip_sock.close()


def udp_recv(ip_sock):
    while True:
        try:
            data, ADDR = ip_sock.recvfrom(1024)
        except:
            break
        data = data.decode('utf-8')
        print("[localtime] {0} \t  服务器端消息：{1}".format(
            time.asctime(time.localtime()), data))
        
        if (data=='quit'):
            conn = False
            break
    
    ip_sock.close()

def main():
    ip_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    t_send = threading.Thread(target=udp_send,args=(ip_sock,))
    t_recv = threading.Thread(target=udp_recv,args=(ip_sock,))
    t_send.start()
    t_recv.start()

if __name__ ==  '__main__':
    main()